/* 
%include "/projects/hsieh_project/code_0_general/m_sum_by_status.sas" /source2;

Macros that sums up selected variables based on unit status.
*/

/*
================================================================================
Sum by status for a given year

dsi_in = input data
dsi_out = output data
pv_by = sum by group
pv_status = unit status
year1 = inital year
year2 = terminal year
*/

%macro m_sum_by_status_core(dsi_in= , dsi_out= , pv_by= , pv_status= , pv_sum= , p_year1= , p_year2= );

%put --------------------------------------------------------------------------------;
%put Now Sum By Status;
%put Dataset &dsi_in.;
%put By &pv_by. &pv_status._&p_year1._&p_year2.;
%put Sum &pv_sum.;

data &dsi_out._&p_year1._&p_year2.;
  set &dsi_in.;
  if &pv_status._&p_year1._&p_year2. = . then delete;
run;

proc sort data=&dsi_out._&p_year1._&p_year2.;
  by &pv_by. &pv_status._&p_year1._&p_year2.;
run;

proc means data=&dsi_out._&p_year1._&p_year2. noprint;
  by &pv_by. &pv_status._&p_year1._&p_year2.;
  output out=&dsi_out._&p_year1._&p_year2.(drop=_type_ _freq_) sum(&pv_sum.)=&pv_sum.;
run;

%Let iv = 1;
%Let code_rename=;
%do %while (%scan(%bquote(&pv_sum), &iv.) ~= );
  
  %Let ivold = %scan(%bquote(&pv_sum), &iv.);
  %Let code_rename = &code_rename. &ivold.=&ivold._stat;
  
  %Let iv = %eval(&iv. + 1);
%end;

%Put rename pv_sum: &code_rename.;

data &dsi_out._&p_year1._&p_year2.;
  set &dsi_out._&p_year1._&p_year2.;
  year_stat1=%eval(&p_year1.);
  year_stat2=%eval(&p_year2.);
  rename &pv_status._&p_year1._&p_year2.=&pv_status.;
  rename &code_rename.;
run;
%mend;


/*
================================================================================
Sum by status for selected year pairs

dsi_in = input data
dsi_out = output data
pv_by = sum by group
pv_status = unit status
pl_year = list of years
*/

%macro m_sum_by_status(dsi_in= , dsi_out= , pv_by= , pv_status= , pv_sum=%bquote(emp est pay), pl_year= );

/* Run the first-last year first */
%Let n_year=%sysfunc(countW(%bquote(&pl_year.)));

%Let i_year1=%scan(%bquote(&pl_year), 1);
%Let i_year2=%scan(%bquote(&pl_year), &n_year.);

%m_sum_by_status_core(dsi_in=&dsi_in., dsi_out=&dsi_out., pv_by=%bquote(&pv_by.), pv_status=&pv_status., pv_sum=%bquote(&pv_sum.), p_year1=&i_year1., p_year2=&i_year2.);

data &dsi_out.;
  set &dsi_out._&i_year1._&i_year2.;
run;

/* Run other year pairs */
%Let i_list = 2;
%do %while (%scan(%bquote(&pl_year), &i_list) ~= );
  %Let i_year1=%scan(%bquote(&pl_year), %eval(&i_list.-1));
  %Let i_year2=%scan(%bquote(&pl_year), &i_list.);
  
  %m_sum_by_status_core(dsi_in=&dsi_in., dsi_out=&dsi_out., pv_by=%bquote(&pv_by.), pv_status=&pv_status., pv_sum=%bquote(&pv_sum.), p_year1=&i_year1., p_year2=&i_year2.);
  
  data &dsi_out.;
    set &dsi_out. &dsi_out._&i_year1._&i_year2.;
  run;
  
  %Let i_list = %eval(&i_list + 1);
%end;
  
%mend;

/* End of SAS file */